
// INCLUDES ********************************************************************

#include "Timer.h"

#include "Function.h"

#include <chrono>

#include <thread>

// NAMESPACES ******************************************************************

namespace
{
    void DelayFunction( Meteor::Function* callback, const uint64_t duration)
    {
        std::this_thread::sleep_for( std::chrono::microseconds(duration));
        
        ( *callback)();
        
        delete callback;
    }
}

// CONSTANTS *******************************************************************

const float Meteor::Timer::ConversionFactor = 1e6;

#pragma mark -
#pragma mark Delayed functions
// -----------------------------------------------------------------------------

const uint64_t Meteor::Timer::GetCurrentTime()
{
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    
    std::chrono::system_clock::duration absolutTime = now.time_since_epoch();
    
    std::chrono::system_clock::rep microSeconds;
    
    microSeconds = std::chrono::duration_cast<std::chrono::microseconds>( absolutTime).count();
    
    return microSeconds;
}


#pragma mark -
#pragma mark Delayed functions
// -----------------------------------------------------------------------------

void Meteor::Timer::CallFunctionWithDelay( Meteor::Function* function, const float delay)
{
    uint64_t duration = delay*Timer::ConversionFactor;

    std::thread delayThread( DelayFunction, function, duration);
    
    delayThread.detach();
}
